import 'package:mobx/mobx.dart';
import '../models/chat_model.dart';

// 这行代码让MobX代码生成器生成代码
part 'chat_store.g.dart';

// 使用混入模式，将自动生成的 _$ChatStore 与我们的类组合
class ChatStore = _ChatStore with _$ChatStore;

// 抽象类定义，用于MobX代码生成
abstract class _ChatStore with Store {
  // 聊天列表 - 使用 @observable 标记为可观察状态
  @observable
  ObservableList<ChatListItem> chatList = ObservableList<ChatListItem>();

  // 当前选中的聊天ID
  @observable
  String? currentChatId;

  // 聊天消息 - 使用Map存储不同聊天的消息列表
  @observable
  ObservableMap<String, ObservableList<ChatMessage>> chatMessages =
      ObservableMap<String, ObservableList<ChatMessage>>();

  // 底部导航栏索引
  @observable
  int currentBottomNavIndex = 0;

  // 获取当前聊天的消息列表
  @computed
  ObservableList<ChatMessage> get currentMessages =>
      currentChatId != null && chatMessages.containsKey(currentChatId)
      ? chatMessages[currentChatId]!
      : ObservableList<ChatMessage>();

  // 获取当前聊天的聊天项
  @computed
  ChatListItem? get currentChatItem => chatList.firstWhere(
    (item) => item.id == currentChatId,
    orElse: () => ChatListItem(
      id: '',
      name: '',
      avatar: '',
      lastMessage: '',
      lastMessageTime: DateTime.now(),
    ),
  );

  // 更改底部导航栏索引 - 使用 @action 标记为动作
  @action
  void setBottomNavIndex(int index) {
    currentBottomNavIndex = index;
  }

  // 选择一个聊天
  @action
  void selectChat(String chatId) {
    currentChatId = chatId;
  }

  // 发送消息
  @action
  void sendMessage(String content) {
    if (currentChatId == null || content.trim().isEmpty) return;

    // 创建新消息
    final message = ChatMessage(
      id: DateTime.now().millisecondsSinceEpoch.toString(),
      senderId: 'me', // 假设当前用户ID为'me'
      content: content,
      timestamp: DateTime.now(),
      isMe: true,
    );

    // 确保存在该聊天的消息列表
    if (!chatMessages.containsKey(currentChatId)) {
      chatMessages[currentChatId!] = ObservableList<ChatMessage>();
    }

    // 添加消息到当前聊天
    chatMessages[currentChatId]!.add(message);

    // 更新最后一条消息和时间
    final index = chatList.indexWhere((item) => item.id == currentChatId);
    if (index != -1) {
      final chat = chatList[index];
      final updatedChat = ChatListItem(
        id: chat.id,
        name: chat.name,
        avatar: chat.avatar,
        lastMessage: content,
        lastMessageTime: DateTime.now(),
        unreadCount: 0, // 自己发送的消息不计入未读
        isOnline: chat.isOnline,
      );
      chatList[index] = updatedChat;
    }
  }

  // 初始化数据 - 通常在应用启动时调用
  @action
  void initData() {
    // 初始化聊天列表（模拟数据）
    chatList = ObservableList.of([
      ChatListItem(
        id: '1',
        name: '张三',
        avatar: 'https://via.placeholder.com/50',
        lastMessage: '明天见!',
        lastMessageTime: DateTime.now().subtract(const Duration(minutes: 5)),
        unreadCount: 0,
        isOnline: true,
      ),
      ChatListItem(
        id: '2',
        name: '李四',
        avatar: 'https://via.placeholder.com/50',
        lastMessage: '好的，我会准时到的',
        lastMessageTime: DateTime.now().subtract(const Duration(hours: 1)),
        unreadCount: 2,
        isOnline: false,
      ),
      ChatListItem(
        id: '3',
        name: '王五',
        avatar: 'https://via.placeholder.com/50',
        lastMessage: '谢谢你的帮助',
        lastMessageTime: DateTime.now().subtract(const Duration(days: 1)),
        unreadCount: 0,
        isOnline: true,
      ),
    ]);

    // 初始化消息列表（模拟数据）
    final messages1 = ObservableList<ChatMessage>.of([
      ChatMessage(
        id: '101',
        senderId: '1',
        content: '你好，明天我们几点见面？',
        timestamp: DateTime.now().subtract(const Duration(minutes: 30)),
        isMe: false,
      ),
      ChatMessage(
        id: '102',
        senderId: 'me',
        content: '下午3点，老地方见',
        timestamp: DateTime.now().subtract(const Duration(minutes: 25)),
        isMe: true,
      ),
      ChatMessage(
        id: '103',
        senderId: '1',
        content: '好的，明天见!',
        timestamp: DateTime.now().subtract(const Duration(minutes: 5)),
        isMe: false,
      ),
    ]);

    chatMessages['1'] = messages1;

    final messages2 = ObservableList<ChatMessage>.of([
      ChatMessage(
        id: '201',
        senderId: 'me',
        content: '会议安排在周四下午2点',
        timestamp: DateTime.now().subtract(const Duration(hours: 3)),
        isMe: true,
      ),
      ChatMessage(
        id: '202',
        senderId: '2',
        content: '好的，我会准时到的',
        timestamp: DateTime.now().subtract(const Duration(hours: 1)),
        isMe: false,
      ),
    ]);

    chatMessages['2'] = messages2;

    final messages3 = ObservableList<ChatMessage>.of([
      ChatMessage(
        id: '301',
        senderId: '3',
        content: '能帮我看一下这个问题吗？',
        timestamp: DateTime.now().subtract(const Duration(days: 2)),
        isMe: false,
      ),
      ChatMessage(
        id: '302',
        senderId: 'me',
        content: '没问题，已经解决了',
        timestamp: DateTime.now().subtract(const Duration(days: 1, hours: 2)),
        isMe: true,
      ),
      ChatMessage(
        id: '303',
        senderId: '3',
        content: '谢谢你的帮助',
        timestamp: DateTime.now().subtract(const Duration(days: 1)),
        isMe: false,
      ),
    ]);

    chatMessages['3'] = messages3;
  }
}
